<template>
  <div>
    <el-select v-model="record.role" :placeholder="$t('请选择角色')" size="small" @change="listData">
      <el-option v-for="item in userList" :key="item.role" :label="item.role" :value="item.role"></el-option>
    </el-select>
    <el-button type="success" size="small" @click="saveUserMenu">{{$t('保存')}}</el-button>
    <el-tree :props="props" class="userTree" ref="userTree" :data="menuList" node-key="id" :indent='22' show-checkbox @check-change="handleCheckChange">
    </el-tree>
  </div>
</template>
<script>
import { getRoleMap, editRole, getRoleArray } from '@/api/user/userMenu'

export default {
  name: 'userMenu',
  // splitPane
  data () {
    return {
      userList: [],
      menuList: [],
      record: {
        role: '',
        role_map: []
      },
      roleList: [],
      props: {
        label: 'name',
        children: 'child'
      }
    }
  },
  created () {
    getRoleArray().then(res => {
      if (res.status === 0) {
        this.userList = res.info
        this.record.role = res.info[0].role
        this.listData(this.record.role)
      }
    })
  },
  methods: {
    handleCheckChange (data, value) {
      this.record.role_map = this.$refs.userTree.getCheckedKeys(false).concat(this.$refs.userTree.getHalfCheckedKeys(false))
    },
    // 列表
    listData (data) {
      if (data) {
        getRoleMap({ role: data }).then(res => {
          if (res.status === 0) {
            this.menuList = res.info
            this.roleList = []
            this.roleArrayArrange(this.menuList)
            this.$refs.userTree.setCheckedKeys(this.roleList, true)
          }
        })
      }
    },
    saveUserMenu (data, type) {
      var formData = JSON.parse(JSON.stringify(this.record))
      formData.role_map = JSON.stringify(formData.role_map)
      editRole(formData).then(res => {
        if (res.status === 0) {
          this.$message({
            message: this.$t('保存成功'),
            type: 'success'
          })
        }
      })
    },
    roleArrayArrange (list) {
      for (let item of list) {
        if (item.child && item.child.length > 0) {
          this.roleArrayArrange(item.child)
        } else if (item.is_show === '1') {
          this.roleList.push(item.id)
        }
      }
    }
  }
}
</script>
<style lang="less">
.userContainer {
  height: calc(100vh - 138px);
}
.userPaneL {
  padding: 0;
  margin: 0;
  background-color: #fff;
  font-size: 18px;
  border-right: 1px solid #ddd;
  width: 240px !important;
}
.userTree {
  margin-top: 10px;
  overflow-x: auto;
  height: calc(100vh - 185px);
  margin-right: 10px;
  line-height: 22px;
}
</style>
